<?php
require_once '../utils/Database.php';
require_once '../utils/Response.php';
require_once '../config/database.php';

class SubscribeMessageService {
    private $appId;
    private $appSecret;
    private $db;
    
    public function __construct() {
        // 使用已有的配置文件中的微信小程序配置
        $this->appId = WX_APPID;
        $this->appSecret = WX_SECRET;
        $this->db = new Database();
    }
    
    // 获取访问令牌
    private function getAccessToken() {
        $cacheKey = 'wechat_access_token';
        
        // 尝试从缓存获取
        $cachedToken = $this->getCachedToken($cacheKey);
        if ($cachedToken) {
            return $cachedToken;
        }
        
        // 从微信API获取新的访问令牌
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";
        
        $response = $this->httpGet($url);
        $data = json_decode($response, true);
        
        if (isset($data['access_token'])) {
            // 缓存访问令牌（有效期7200秒，提前5分钟过期）
            $this->cacheToken($cacheKey, $data['access_token'], 6900);
            return $data['access_token'];
        }
        
        throw new Exception('获取微信访问令牌失败: ' . ($data['errmsg'] ?? 'Unknown error'));
    }
    
    // 发送订阅消息
    public function sendSubscribeMessage($openid, $templateId, $data, $page = '', $miniProgramState = 'formal') {
        try {
            $accessToken = $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$accessToken}";
            
            $postData = [
                'touser' => $openid,
                'template_id' => $templateId,
                'data' => $data,
                'miniprogram_state' => $miniProgramState
            ];
            
            if (!empty($page)) {
                $postData['page'] = $page;
            }
            
            $response = $this->httpPost($url, json_encode($postData, JSON_UNESCAPED_UNICODE));
            $result = json_decode($response, true);
            
            // 记录发送日志
            $this->logMessageSend($openid, $templateId, $data, $result);
            
            if ($result['errcode'] === 0) {
                return [
                    'success' => true,
                    'message' => '消息发送成功',
                    'msgid' => $result['msgid'] ?? null
                ];
            } else {
                return [
                    'success' => false,
                    'error_code' => $result['errcode'],
                    'error_message' => $result['errmsg'],
                    'message' => '消息发送失败: ' . $result['errmsg']
                ];
            }
        } catch (Exception $e) {
            error_log('发送订阅消息异常: ' . $e->getMessage());
            return [
                'success' => false,
                'message' => '消息发送异常: ' . $e->getMessage()
            ];
        }
    }
    
    // 发送预约成功通知
    public function sendReservationSuccessMessage($openid, $reservationData) {
        $templateId = 'template_reservation_success';
        
        $data = [
            'thing1' => ['value' => $reservationData['project'] ?? '校史馆参观'],
            'date2' => ['value' => $reservationData['date'] ?? ''],
            'time3' => ['value' => $reservationData['time'] ?? ''],
            'thing4' => ['value' => $reservationData['tips'] ?? '请按时到馆参观，携带有效身份证件']
        ];
        
        return $this->sendSubscribeMessage($openid, $templateId, $data);
    }
    
    // 发送预约审核通知
    public function sendReservationApprovalMessage($openid, $reservationData) {
        $templateId = $reservationData['status'] === 'approved' 
            ? 'template_reservation_approved' 
            : 'template_reservation_rejected';
        
        $statusText = $reservationData['status'] === 'approved' ? '审核通过' : '审核拒绝';
        
        $data = [
            'thing1' => ['value' => $reservationData['project'] ?? '校史馆参观'],
            'phrase2' => ['value' => $statusText],
            'date3' => ['value' => $reservationData['date'] ?? ''],
            'thing4' => ['value' => $reservationData['notes'] ?? '']
        ];
        
        return $this->sendSubscribeMessage($openid, $templateId, $data);
    }
    
    // 发送团队预约审核通知
    public function sendTeamReservationApprovalMessage($openid, $teamData) {
        $templateId = $teamData['status'] === 'approved' 
            ? 'template_team_approved' 
            : 'template_team_rejected';
        
        $statusText = $teamData['status'] === 'approved' ? '审核通过' : '审核拒绝';
        
        $data = [
            'thing1' => ['value' => $teamData['team_name'] ?? ''],
            'phrase2' => ['value' => $statusText],
            'date3' => ['value' => $teamData['date'] ?? ''],
            'thing4' => ['value' => $teamData['notes'] ?? '']
        ];
        
        return $this->sendSubscribeMessage($openid, $templateId, $data);
    }
    
    // 发送志愿者申请审核通知
    public function sendVolunteerApprovalMessage($openid, $volunteerData) {
        $templateId = $volunteerData['status'] === 'approved' 
            ? 'template_volunteer_approved' 
            : 'template_volunteer_rejected';
        
        $statusText = $volunteerData['status'] === 'approved' ? '审核通过' : '审核拒绝';
        
        $data = [
            'thing1' => ['value' => $volunteerData['position'] ?? '讲解志愿者'],
            'phrase2' => ['value' => $statusText],
            'date3' => ['value' => $volunteerData['service_date'] ?? ''],
            'thing4' => ['value' => $volunteerData['notes'] ?? '']
        ];
        
        return $this->sendSubscribeMessage($openid, $templateId, $data);
    }
    
    // 发送活动申请审核通知
    public function sendActivityApprovalMessage($openid, $activityData) {
        $templateId = $activityData['status'] === 'approved' 
            ? 'template_activity_approved' 
            : 'template_activity_rejected';
        
        $statusText = $activityData['status'] === 'approved' ? '审核通过' : '审核拒绝';
        
        $data = [
            'thing1' => ['value' => $activityData['activity_name'] ?? ''],
            'phrase2' => ['value' => $statusText],
            'date3' => ['value' => $activityData['activity_date'] ?? ''],
            'thing4' => ['value' => $activityData['notes'] ?? '']
        ];
        
        return $this->sendSubscribeMessage($openid, $templateId, $data);
    }
    
    // 批量发送消息
    public function batchSendMessages($messages) {
        $results = [];
        
        foreach ($messages as $message) {
            $result = $this->sendSubscribeMessage(
                $message['openid'],
                $message['template_id'],
                $message['data'],
                $message['page'] ?? '',
                $message['miniprogram_state'] ?? 'formal'
            );
            
            $results[] = [
                'openid' => $message['openid'],
                'result' => $result
            ];
            
            // 避免频率限制，稍微延迟
            usleep(100000); // 0.1秒
        }
        
        return $results;
    }
    
    // HTTP GET请求
    private function httpGet($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode !== 200) {
            throw new Exception("HTTP请求失败，状态码: {$httpCode}");
        }
        
        return $response;
    }
    
    // HTTP POST请求
    private function httpPost($url, $data) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data)
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode !== 200) {
            throw new Exception("HTTP请求失败，状态码: {$httpCode}");
        }
        
        return $response;
    }
    
    // 缓存访问令牌
    private function cacheToken($key, $token, $expiry) {
        $cacheFile = sys_get_temp_dir() . '/' . md5($key) . '.cache';
        $data = [
            'token' => $token,
            'expire_time' => time() + $expiry
        ];
        file_put_contents($cacheFile, serialize($data));
    }
    
    // 获取缓存的访问令牌
    private function getCachedToken($key) {
        $cacheFile = sys_get_temp_dir() . '/' . md5($key) . '.cache';
        
        if (!file_exists($cacheFile)) {
            return null;
        }
        
        $data = unserialize(file_get_contents($cacheFile));
        
        if (!$data || time() >= $data['expire_time']) {
            unlink($cacheFile);
            return null;
        }
        
        return $data['token'];
    }
    
    // 记录消息发送日志
    private function logMessageSend($openid, $templateId, $data, $result) {
        try {
            $sql = "INSERT INTO subscribe_message_logs (openid, template_id, message_data, send_result, created_at) VALUES (?, ?, ?, ?, NOW())";
            $this->db->execute($sql, [
                $openid,
                $templateId,
                json_encode($data, JSON_UNESCAPED_UNICODE),
                json_encode($result, JSON_UNESCAPED_UNICODE)
            ]);
        } catch (Exception $e) {
            error_log('记录消息发送日志失败: ' . $e->getMessage());
        }
    }
}

// API接口处理
$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);
$action = $_GET['action'] ?? '';

$service = new SubscribeMessageService();

switch ($method) {
    case 'POST':
        switch ($action) {
            case 'send':
                // 发送单条消息
                if (empty($input['openid']) || empty($input['template_id']) || empty($input['data'])) {
                    Response::error('缺少必要参数');
                }
                
                $result = $service->sendSubscribeMessage(
                    $input['openid'],
                    $input['template_id'],
                    $input['data'],
                    $input['page'] ?? '',
                    $input['miniprogram_state'] ?? 'formal'
                );
                
                if ($result['success']) {
                    Response::success($result, '消息发送成功');
                } else {
                    Response::error($result['message']);
                }
                break;
                
            case 'send_batch':
                // 批量发送消息
                if (empty($input['messages']) || !is_array($input['messages'])) {
                    Response::error('缺少消息列表');
                }
                
                $results = $service->batchSendMessages($input['messages']);
                Response::success($results, '批量发送完成');
                break;
                
            case 'send_reservation_success':
                // 发送预约成功通知
                if (empty($input['openid']) || empty($input['reservation_data'])) {
                    Response::error('缺少必要参数');
                }
                
                $result = $service->sendReservationSuccessMessage($input['openid'], $input['reservation_data']);
                
                if ($result['success']) {
                    Response::success($result, '预约成功通知发送成功');
                } else {
                    Response::error($result['message']);
                }
                break;
                
            case 'send_reservation_approval':
                // 发送预约审核通知
                if (empty($input['openid']) || empty($input['reservation_data'])) {
                    Response::error('缺少必要参数');
                }
                
                $result = $service->sendReservationApprovalMessage($input['openid'], $input['reservation_data']);
                
                if ($result['success']) {
                    Response::success($result, '预约审核通知发送成功');
                } else {
                    Response::error($result['message']);
                }
                break;
                
            case 'send_team_approval':
                // 发送团队预约审核通知
                if (empty($input['openid']) || empty($input['team_data'])) {
                    Response::error('缺少必要参数');
                }
                
                $result = $service->sendTeamReservationApprovalMessage($input['openid'], $input['team_data']);
                
                if ($result['success']) {
                    Response::success($result, '团队预约审核通知发送成功');
                } else {
                    Response::error($result['message']);
                }
                break;
                
            case 'send_volunteer_approval':
                // 发送志愿者审核通知
                if (empty($input['openid']) || empty($input['volunteer_data'])) {
                    Response::error('缺少必要参数');
                }
                
                $result = $service->sendVolunteerApprovalMessage($input['openid'], $input['volunteer_data']);
                
                if ($result['success']) {
                    Response::success($result, '志愿者审核通知发送成功');
                } else {
                    Response::error($result['message']);
                }
                break;
                
            case 'send_activity_approval':
                // 发送活动审核通知
                if (empty($input['openid']) || empty($input['activity_data'])) {
                    Response::error('缺少必要参数');
                }
                
                $result = $service->sendActivityApprovalMessage($input['openid'], $input['activity_data']);
                
                if ($result['success']) {
                    Response::success($result, '活动审核通知发送成功');
                } else {
                    Response::error($result['message']);
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    default:
        Response::error('不支持的请求方法');
}
?>